Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

87
Views
How do I make `foo[1] ==1; foo[1][2]==3; foo[1][2][3]==6` work in JavaScript?

How do I define foo to make the following code work correctly as expected (in JavaScript)?

foo[1] + 1             // 2
foo[1][2] + 1          // 4
foo[10][20][30] + 1    // 61
foo[100][200][300] + 1 // 601

This is an interview question I once met.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This sounds like a new take on the old variadic chainable sum function puzzle, with proxy member access instead of function calls. The possible approaches are still the same though, and the …+1 gives away that they are looking for the valueOf solution. In the same vein, foo+1 would be 1 and +foo/Number(foo) would be 0.

const handler = {
    get(target, propName, receiver) {
        if (typeof propName == 'string' && /^\d+$/.test(propName))
            return sumProxy(target + parseInt(propName, 10));
        else
            return Reflect.get(target, propName, receiver);
    }
};
function sumProxy(value) {
    return new Proxy({
        valueOf() { return value; }
    }, handler);
}
const foo = sumProxy(0);

console.log(foo + 1);                // 1
console.log(foo[1] + 1);             // 2
console.log(foo[1][2] + 1);          // 4
console.log(foo[10][20][30] + 1);    // 61
console.log(foo[100][200][300] + 1); // 601

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!